<?php


use App\Http\Controllers\API\StatusController;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Response as Responses;
use Illuminate\Support\Facades\Storage;

if (!function_exists('ipAndAddress')){
    //获取ip地址和具体物理地址

    function ipAndAddress($ip='36.189.214.10'):array{
        $url = "https://api.a76yyyy.cn/ip?function=ipInfo&params1={$ip}";
        $client = http::get($url);
        try {
//                    "IP地址": "124.117.144.187",
//                    "IP段起始地址": "124.117.118.0",
//                    "IP段结束地址": "124.117.194.255",
//                    "国家/地区/组织": "中国",
//                    "省/自治区/直辖市": "新疆",
//                    "地级市": "乌鲁木齐市",
//                    "县/区/镇/街道": "",
//                    "详细地址": "新疆乌鲁木齐市",
//                    "运营商/节点": "电信",
//                    "数据库": "2022年04月29日纯真IP数据"
            $data = $client->json()['data'];
            return [
                'address'=>$data["国家/地区/组织"].' | '.$data["省/自治区/直辖市"].' | '.$data["地级市"],
                'operators'=>$data["运营商/节点"]
            ];
        }catch (\Throwable $e){}
        return  [];

    }
}
if(!function_exists('Success')){

    /**
     * 成功响应
     * @param array|null $data 数据
     * @param string|null $message 警告消息
     * @param int|null $statusCode HTTP请求状态
     * @return \Illuminate\Http\JsonResponse 返回成功响应;
     */
    function Success(string|null $message = null,array|null $data = null ,int|null $statusCode = 200,bool $ip_ify = false): \Illuminate\Http\JsonResponse
    {
        $message ??= trans("auth.success");
        $data_ = [
            'status'=>"✨success",
            "message" => (string)$message,
            "code" => (int)$statusCode,
            "data" => (object)$data
        ];
        if($ip_ify){
            $data_['ipDetail'] = ipAndAddress(request()->ip());
        }
        return Responses::json($data_);
    };
}
if (!function_exists('Fail')){
    /**
     * 失败响应
     * @param array|null $data 数据
     * @param string|null $message 警告消息
     * @param int|null $statusCode HTTP请求状态
     * @return object 返回失败响应;
     */
    function Fail(string|null $message = 'Error' , array|null $data = array() , int|null $statusCode = 422,array|null $error = array()):mixed
    {
        $message ??= trans("response.fail");
        $data_ = [
            'status'=>"⛔ fail",
            "message" => (string)$message,
            "code" => (int)$statusCode,
            "data" => (object)$data,
            "error"=>(object)$error
        ];
        return Responses::json($data_);
    }
}

if(!function_exists("Message")){
    /**
     * 自定义消息
     * @param string|null $message 消息内容
     * @param int|null $statusCode 状态
     *statusCode -》 响应状态
     * @return void
     */
    function Message(string|null $message = null,int|null $statusCode = 888):void
    {
        if($message === null)
        $message = __("http-statuses.{$statusCode}");
         abort($statusCode,$message);
    }
}


#设置语言

if (!function_exists('setLang')){

    /**
     * 设置语言
     */
    function setLang():void{
        if(!empty(request()->header('lang')) && request()->header('lang') ===(string)request()->header('lang') ){
            if((string)request()->header('lang') === 'ug')
                app()->setLocale('ug');
            else
                app()->setLocale('zh_CN');
        }
    }
}
if (!function_exists('getLang')){

    /**
     *获取当前语言:标准值 ug|zh
     */
    function getLang():string
    {
        if(app()->getLocale() === 'ug')
            return 'ug';
        return 'zh';
    }
}


if (!function_exists('del_unset')){
    /**
     * 删除模型中的某一个，或者多个字段
     * @param mixed $request 数据库查询的数据
     * @param array $unset_parameters
     * @param int $type
     * @return object|array $request 返回删除后的数据
     */
    function del_unset (object|array $request, array $unset_parameters, int $type = 0): object|array
    {
        if($type === 2){//多遇到的删除字段
            $unset_parameters = [
                'id',
                'deleted_at',
                'updated_at'
                //'created_at'
            ];
        }
        if(is_array($request))$count = count($request);
        else $count = $request->count();
        if($count === 1){
            foreach ($unset_parameters as $item){
                if(!empty($request[$item]))
                    unset($request[$item]);
            }
            return $request;
        }

        foreach ($request as $key=>$res){
            foreach ($unset_parameters as $item){
                if(!empty($request[$key][$item]))
                    unset($request[$key][$item]);
            }
        }
        return $request;
    }
}

if (!function_exists('FormatName')){

    /**
     *语言格式化: 单独列出来后缀为_ug,_zh 的所有字段的当前语言值；
     *@param object|array $restaurantData 需要格式化的数据
     *
     * */
    function FormatName(object|array $restaurantData): object|array
    {
        $lang = getLang();
        if(gettype($restaurantData) !== 'array') {
            if($restaurantData->count() === 0)return $restaurantData;
            $restaurantData1 = $restaurantData->toArray();
        }
        else{
            if(count($restaurantData) === 0)return $restaurantData;
            $restaurantData1 = $restaurantData;
        }
        foreach ($restaurantData1 as $key => $value) {
            if($value === null) {
                $restaurantData[$key] = '';
                continue;
            }
            $name = explode("_u", $key);
            if (!empty($name[1]) && strlen($name[1]) === 1) {
                $name = explode("_ug", $key);
                $restaurantData[$name[0]] = $restaurantData[$name[0] . '_' . $lang];
            }
            if(str_contains($key, "image") || $key === 'cover' || $key === 'logo')
            {
                $restaurantData[$key] = getFileUrl($value);
            }

            if(str_contains($key, "url"))
            {
                if(!empty(explode('app_version',$value)[1])){
                    $restaurantData[$key] = Storage::disk('app_version')->url($value) ?? '';
                }

            }
        }

        return $restaurantData;
    }
}

if (!function_exists('LikeFun')){

    /**
     *sql模糊查询时:字符串转义
     */
    function LikeFun($str): array|string
    {
        $like_escape_char = '!';

        return str_replace([$like_escape_char, '%', '_'], [
            $like_escape_char.$like_escape_char,
            $like_escape_char.'%',
            $like_escape_char.'_',
        ], $str);
    }
}


if (!function_exists('PasswordAuth')){

    /**
     * 密码验证
     * @param string $password 用户输入的密码
     * @param string $db_password 数据库获取的密码
     * @return bool 验证结果
     * */
    function PasswordAuth(string $password,string $db_password):bool{
        if(!Hash::check($password,$db_password))
            return false;
        return false;
    }
}

if (!function_exists('PasswordImport')){

    /**
     * 密码加密
     * @param string $password 需要Hash加密的数据
     * @return string Hash加密的数据
     * */
    function PasswordImport(string $password):string{
        return Hash::make($password);
    }
}

if (!function_exists('ImageAuth')){

    /**
     *[需要去除图片地址里的网站域名]
     * @param  $image string 客户端发送的图片
     * @return string 标准的数据库图片地址
     * */
    function ImageAuth(string $image):string{
        $newImage = '';
        try {
            $res = explode(env('APP_URL').'/storage',$image);
            if(Storage::disk('public')->exists($res[1]))
                $newImage = '/storage'.$res[1];
        }catch (Throwable $e){
            Message(trans('file.file_image_exists'));
        }
        return  $newImage;
    }
}

if (!function_exists('getFileUrl')){

    /**
     *完整地址
     * @param  $image string 图片
     * @return string 完整的图片地址
     * */
    function getFileUrl(string $image):string{
        $img_null = asset('assets/image/image_null.png');
        $organFileName = 'files/MaYi';
        if(str_contains($image, $organFileName)){
            $img_s = explode($organFileName,$image);
            try {
                $img = $organFileName.$img_s[1];
                if(Storage::disk('public')->exists($img))
                    return Storage::disk('public')->url($img);

            }catch (Throwable $e){}
        }
        return $img_null;
    }
}

if (!function_exists('setFileUrl')){

    /**
     *[保存数据库的图片地址]
     * @param  $image string 图片地址 #http://rms20.munber.vip/storage/uploads/M_1/20231223/165112ali1703321472.jpg
     * @return string 生成适合保存数据库的图片地址
     */
    function setFileUrl(string $image):string{

        $organFileName = 'files/MaYi';
        if(str_contains($image, $organFileName)){
            $img_s = explode($organFileName,$image);
            try {
                $img = $organFileName.$img_s[1];
                if(Storage::disk('public')->exists($img))
                    return $img;

            }catch (Throwable $e){}
        }
         Message(__('file.file_image_exists'));
        return '';
    }
}

if (!function_exists('PhoneAuth')){
    /**
     *手机号验证；
     * @param  $phone string 手机号
     * @param bool $ify
     * @return bool|array 判断是否为一个合法的手机号
     */
    function PhoneAuth(string $phone, bool $ify = false):bool|array{
        $auth_sefer = '/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/';
        if(!preg_match($auth_sefer,$phone)){
            if($ify){
                return ['ify'=>false,'msg'=>__('msg.phone_error')];
            }
              Message(__('msg.phone_error'));

        }
        return true;

    }

}


if (!function_exists('JsonFormatArray')){

    /**
     * Json数据格式化为数组
     * @return array 格式化好的数据
     **/
    function JsonFormatArray($data):array{
        foreach ($data as $key=>$item) {
            if ($item === null) {
                $data->{$key} = '';
                continue;
            }
            if (is_string($item) && !empty(explode( '{',$item)[1])){
                $item = json_decode(stripslashes($item));

                if(is_object($item))
                    $data->{$key}  = $item;
            }
            if (is_array($item)) $data->{$key} = (array)$item[0];
            if(is_object($item)) $data->{$key} = JsonFormatArray($item);
        }
        return (array)$data;
    };
}

if (!function_exists('FormatString')){
    /**
     *移除转义符号
     * @param string $string 需要去除转义的字符串
     * @return  array 返回对应的数据
     * */
    function FormatString(string $string):array{
        return (array)json_decode(stripslashes($string));
    }
}


if (!function_exists('DownLoad')){
    /**
      下载
      @param string $url
     **/
    function DownLoad(string $url): \Symfony\Component\HttpFoundation\BinaryFileResponse
    {
        $urlArray = explode('.',$url);
        if(count($urlArray)>1){
            $newUrl = "download{$urlArray[count($urlArray) - 1]}";
        }
        else $newUrl = $url;

        return response()->download($url,$newUrl);
    }
}

if (!function_exists('FormatTheStars')){//星星格式化157*****317
    /**
     * @param $num1 int 起始位置
     * @param $num2 int 终点位置
     * @param $string string 部分转换星星的字符串
     * */
    function FormatTheStars (int $num1, int $num2, string $string):string{
        $chars = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
        foreach ($chars as $key => $item){
            if($key >= $num1 && $key <= $num2){
                $chars[$key] = "*";
            }
        }
        return implode($chars);
    }
}


if (!function_exists('ToArray')){

    /**
     * @after Alimjan
     * 字符串转换数组【多出的功能是排查重复元素，移除空元素】
     * @param string $param 拆分符号
     * @param string|null $string 需要转换数组的字符
     * @return array 拆分后的数组
     *
     **/
    function ToArray(string|null $string,string $param = ','):array
    {
        return array_unique(array_filter(explode("{$param}",(string)$string)));
    }
}

if (!function_exists('getFileTypeInfo')){
    /**
     * 获取文件类型和对应名字
     * @param $filename
     * @return array|string
     */
    function getFileTypeInfo($filename,$ify = false): string|array
    {
        // 获取文件扩展名并转换为小写，以确保不区分大小写
        $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

        // 定义文件类型和类型名称的映射，使用更紧凑的数组格式

        // 定义一个函数来查找文件类型
        $getType = function($ext) use($ify){
            $fileTypeMapping = [
                'image' => [
                    'size'=>2,
                    'types'=>['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'svg']
                ],
                'document' => [
                    'size'=>5,
                    'types'=>['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']
                ],
                'audio' => [
                    'size'=>6,
                    'types'=>['mp3', 'wav', 'ogg', 'flac','m4a']
                ],
                'video' => [
                    'size'=>100,
                    'types'=>['mp4', 'avi', 'mov', 'mkv', 'flv']
                ],
                'archive' => [
                    'size'=>100,
                    'types'=>['zip', 'rar', 'gz', 'tar']
                ],
                'text' => [
                    'size'=>2,
                    'types'=>['txt', 'md', 'csv']
                ],
                'code' => [
                    'size'=>2,
                    'types'=>['html', 'php', 'js', 'css', 'json', 'xml']
                ],
            ];
            foreach ($fileTypeMapping as $type => $extensions) {
                if (in_array($ext, $extensions['types'])) {
                    $arr = [
                        'type' => $type,
                        'size'=>$extensions['size'],
                        'name' => __("file.types.{$type}")
                    ];
                    if($ify)return  $arr;
                    return  $arr['name'];
                }
            }
            return ['type' => 'unknown', 'name' => '未知文件'];
        };

        // 返回匹配的文件类型和类型名称
        return $getType($extension);
    }
}
